import axios from 'axios'
import {ElNotification} from 'element-plus'
import {$cache} from "@util/cache.ts";

// 创建axios实例
const $axios = axios.create({
    timeout: 24 * 60 * 60 * 1000
})

// request拦截器
$axios.interceptors.request.use(config => {
    const {url, method, baseURL} = config
    config.headers["Authorization"] = $cache.getAccessToken();
    config.headers["token"] = $cache.getAccessToken();

    // "eyJ1c2VySWQiOiI2NjM5OTgyMjA0MTUwNDUiLCJ1c2VybmFtZSI6Imh3MDAzIiwibmlja25hbWUiOiLlro/mlocwMDMiLCJkZXB0SWQiOiIwMSIsImFyZWFJZCI6IiIsInBob25lIjoiIiwiZW1haWwiOiIiLCJkZXB0TmFtZSI6IuS4nOWMl+mHjuWkluiZjuixueermSIsImFyZWFOYW1lIjoiIiwiYXZhdGFyIjoiIiwiZGVwdExldmVsIjoxLCJhcmVhTGV2ZWwiOjAsInJvbGUiOiJod3dianMifQ==";
    // config.params.timestamp = new Date().getTime()

    console.log("Axios 请求地址", config.url)
    return config
}, error => {
    // if (openConsole) ////// //// console.log('响应拦截器 error ===>' + JSON.stringify(error))
    return Promise.reject(error)
})

// 响应拦截器
$axios.interceptors.response.use((res) => {
        // if (openConsole) ////// //// console.log('响应拦截器 response ===>' + JSON.stringify(res))
        const code = res.data.code || 200;
        const message = res.data.message

        // 二进制数据则直接返回
        if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
            return res.data;
        }

        //返回响应内容data
        return Promise.resolve(res.data)
    },
    (error) => {
        // if (openConsole) ////// //// console.log('响应拦截器 error ===>' + JSON.stringify(error))

        let {message, code} = error;
        if (code === "ERR_NETWORK") {
            message = "网路断开或者，服务正在更新，暂时无法访问。";
            // routerPush("/errNetwork")
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            if (error.response.data.msg) {
                message = "访问服务接口失败：" + error.response.data.msg
            } else if (error.response.data.message) {
                message = "访问服务接口失败：" + error.response.data.message
                // message = error.response.data.message ? error.response.data.message : "访问服务接口失败，返回状态码：" + message.substring(message.length - 3);
            }
        }

        // closeError : 不进行统一报错提醒
        if (error.config.closeError && error.config.closeError == '1') return Promise.reject(error)

        // 统一报错提醒
        ElNotification.warning({title: message})
        return Promise.reject(error)

    })


export const HttpContentType = {
    JSON: "application/json;charset=utf-8",
    FORM: "application/x-www-form-urlencoded;charset=utf-8",
    TEXT_PLAIN: 'text/plain;charset=utf-8',
    TEXT_HTML: 'text/html;charset=utf-8',
    MULTIPART_FORM_DATA: 'multipart/form-data',
    OCTET_STREAM: 'application/octet-stream',
}

export const HttpMethod = {
    GET: "get",
    POST: "post",
    PUT: "put",
    DELETE: "delete",
}

export const $http = {
    axios: $axios,
    get: (url: string, params = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, params, headers, method: HttpMethod.GET, ...otherConfig}
        config_.headers = headers;
        return $axios(config_)
    },
    postForm: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.POST, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.FORM, ...headers}
        return $axios(config_)
    },
    postJson: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.POST, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.JSON, ...headers}
        return $axios(config_)
    },
    putForm: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.PUT, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.FORM, ...headers}
        return $axios(config_)
    },
    putJson: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.PUT, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.JSON, ...headers}
        return $axios(config_)
    },
    deleteForm: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.DELETE, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.FORM, ...headers}
        return $axios(config_)
    },
    deleteJson: (url: string, data = {}, headers = {}, otherConfig = {}) => {
        let config_ = {url, data, headers, method: HttpMethod.DELETE, ...otherConfig}
        config_.headers = {"Content-Type": HttpContentType.JSON, ...headers}
        return $axios(config_)
    }

}

